package cn.hznc.webstocket;

import cn.hznc.controller.service.message.MessageService;
import cn.hznc.domain.request.message.GetMessageReq;
import cn.hznc.domain.response.ResponseBody;
import cn.hznc.utils.JwtHelper;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author：Administrator
 * @Date：2024/2/29 11:49
 */
@ServerEndpoint(value = "/websocket")
@Component
public class WebSocketServer{

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    //异步处理响应方法的线程池
    private static final ExecutorService executor = Executors.newFixedThreadPool(1);

    @Autowired
    private MessageService messageService;

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this); //加入set中
        addOnlineCount(); //在线数加1

        try {
            sendMessage("连接成功");
        } catch (IOException e) {

        }
    }
// //连接打开时执行
// @OnOpen
// public void onOpen(@PathParam("user") String user, Session session) {
// currentUser = user;
// System.out.println("Connected ... " + session.getId());
// }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this); //从set中删除
        subOnlineCount(); //在线数减1

    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        if(StringUtils.isBlank(message)){
            return;
        }
        executor.submit(() -> {
            //通过token解析获得用户
            GetMessageReq getMessageReq = JSONObject.parseObject(message, GetMessageReq.class);

            //查询当前用户对应的messageList并返回
            MessageService messageService1 = (MessageService)SpringAware.getContext().getBean("messageService");
            Object messageList = messageService1.getMessageList(getMessageReq);
            //群发消息
            for (WebSocketServer item : webSocketSet) {
                //找到特定的session并将消息发送给该session
                if(!Objects.equals(item.session.getId(), session.getId())){
                    continue;
                }
                try {
                    item.sendMessage(JSONObject.toJSONString(ResponseBody.success(messageList)));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {

        error.printStackTrace();
    }


    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    /**
     * 群发自定义消息
     * */
    public static void sendInfo(String message) throws IOException {

        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}
